package com.hmall.trade.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.api.clients.CartClient;
import com.hmall.api.clients.ItemClient;
import com.hmall.api.dto.ItemDTO;
import com.hmall.api.dto.OrderDetailDTO;
import com.hmall.common.domain.MultiDelayMessage;
import com.hmall.common.exception.BadRequestException;
import com.hmall.common.utils.BeanUtils;
import com.hmall.common.utils.CollUtils;
import com.hmall.common.utils.UserContext;
import com.hmall.trade.constants.TradeMqConstants;
import com.hmall.trade.domain.dto.OrderFormDTO;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.domain.po.OrderDetail;
import com.hmall.trade.mapper.OrderMapper;
import com.hmall.trade.service.IOrderDetailService;
import com.hmall.trade.service.IOrderService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2023-05-05
 */
@Service
@RequiredArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    private final ItemClient itemClient;
    private final IOrderDetailService detailService;
    private final CartClient cartClient;
    private final RabbitTemplate rabbitTemplate;


    @Override
//    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
   @GlobalTransactional
    public Long createOrder(OrderFormDTO orderFormDTO) {
        // 1.订单数据
        Order order = new Order();
        // 1.1.查询商品
        List<OrderDetailDTO> detailDTOS = orderFormDTO.getDetails();
        // 1.2.获取商品id和数量的Map
        Map<Long, Integer> itemNumMap = detailDTOS.stream()
                .collect(Collectors.toMap(OrderDetailDTO::getItemId, OrderDetailDTO::getNum));
        Set<Long> itemIds = itemNumMap.keySet();
        // 1.3.查询商品
        List<ItemDTO> items = itemClient.queryItemByIds(itemIds);
        if (items == null || items.size() < itemIds.size()) {
            throw new BadRequestException("商品不存在");
        }
        // 1.4.基于商品价格、购买数量计算商品总价：totalFee
        int total = 0;
        for (ItemDTO item : items) {
            total += item.getPrice() * itemNumMap.get(item.getId());
        }
        order.setTotalFee(total);
        // 1.5.其它属性
        order.setPaymentType(orderFormDTO.getPaymentType());
        order.setUserId(UserContext.getUser());
        order.setStatus(1);
        // 1.6.将Order写入数据库order表中
        save(order);

        // 2.保存订单详情
        List<OrderDetail> details = buildDetails(order.getId(), items, itemNumMap);
        detailService.saveBatch(details);

        // 3.清理购物车商品
//        cartClient.deleteCartItemByIds(itemIds);
        //使用mq 发送消息清空购物车
        //清空购物车需要订单id和用户id, 不是通过openFeign传递，在购物车没有用户ID，需要我们传递
        //通过map 传递
        // itemIds转化为数组
//        String[] itemIdsss = itemIds.stream().map(String::valueOf).toArray(String[]::new);
//        String join = String.join(",",itemIdsss );
//        Map<String,Object> cartMapByUserIdAndItemId =new HashMap<>();
//        cartMapByUserIdAndItemId.put("itemIds",itemIds);
//        cartMapByUserIdAndItemId.put("userId",UserContext.getUser());
//        rabbitTemplate.convertAndSend("order-exchange","order.delete",cartMapByUserIdAndItemId);
        //使用请求头传递
        rabbitTemplate.convertAndSend("order-exchange", "order.delete", itemIds, new MessagePostProcessor() {
            //在发送消息之前处理请求头
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setHeader("userId", UserContext.getUser());
                return message;
            }
        });

//         int i = 1/0;
        // 4.扣减库存
        try {
            itemClient.deductStock(detailDTOS);
        } catch (Exception e) {
            throw new RuntimeException("库存不足！");
        }
        //在下单完成后，发送延迟消息mq，查询支付状态
        /*
         * 1.发送延迟消息，查询支付状态
         * 2，设置12000毫秒的延迟时间，后去查询订单的支付状态，如果支付成功，则更新订单状态为2，如果支付失败，则更新订单状态为3
         * 3.用户可能没到12000毫秒内，比如5000毫秒就完成支付，我们要等到12000ms后才执行，所以创建一个时间片段，提前执行查询，如果为支付在设置时间片段的等待时间进查询
         * 4.如果用户支付成功，则更新订单状态为2，如果用户超时，则取消订单，放回库存
         */
        MultiDelayMessage<Long> longMultiDelayMessage = MultiDelayMessage.of(order.getId(), 2000);
        rabbitTemplate.convertAndSend(TradeMqConstants.DELAY_EXCHANGE, TradeMqConstants.DELAY_ORDER_ROUTING_KEY, longMultiDelayMessage, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setDelay(1000);
                message.getMessageProperties().setHeader("userId", UserContext.getUser());
                return message;
            }
        });
        return order.getId();
    }

    @Override
    public void markOrderPaySuccess(Long orderId) {
        Order order = new Order();
        order.setId(orderId);
        order.setStatus(2);
        order.setPayTime(LocalDateTime.now());
        updateById(order);
//        lambdaUpdate().eq(Order::getId,orderId).eq(Order::getStatus,1).update();
    }

    @Override
    public void cancelOrder(Long orderId) {
        //取消订单放回库存
        //1、更新订单的状态为已关闭
        lambdaUpdate()
                .set(Order::getStatus, 5)
                .set(Order::getCloseTime, LocalDateTime.now())
                .eq(Order::getId, orderId)
                .eq(Order::getStatus, 1)
                .update();
        //2、回退商品库存；商品的购买数在订单详情中
        //根据订单id查询订单详情
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId, orderId);
        List<OrderDetail> orderDetails = detailService.list(queryWrapper);
        if (CollUtils.isEmpty(orderDetails)) {
            return;
        }
        List<OrderDetailDTO> orderDetailDTOS = BeanUtils.copyList(orderDetails, OrderDetailDTO.class);
        //将购买数量修改为负数
        for (OrderDetailDTO orderDetailDTO : orderDetailDTOS) {
            orderDetailDTO.setNum(-orderDetailDTO.getNum());
        }

        itemClient.deductStock(orderDetailDTOS);
    }

    private List<OrderDetail> buildDetails(Long orderId, List<ItemDTO> items, Map<Long, Integer> numMap) {
        List<OrderDetail> details = new ArrayList<>(items.size());
        for (ItemDTO item : items) {
            OrderDetail detail = new OrderDetail();
            detail.setName(item.getName());
            detail.setSpec(item.getSpec());
            detail.setPrice(item.getPrice());
            detail.setNum(numMap.get(item.getId()));
            detail.setItemId(item.getId());
            detail.setImage(item.getImage());
            detail.setOrderId(orderId);
            details.add(detail);
        }
        return details;
    }
}
